package com.liaoban.app.ui.login;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.VideoView;

import com.liaoban.app.R;
import com.liaoban.app.api.type.ThreeLoginReq;
import com.liaoban.app.api.type.User;
import com.liaoban.app.api.type.event.LocationEvent;
import com.liaoban.app.api.type.event.LoginEvent;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.Constant;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.base.BaseActivity;
import com.liaoban.app.ui.base.BaseLoginActivity;
import com.liaoban.app.ui.common.WebActivity;
import com.liaoban.app.util.CommonUtils;
import com.netease.nim.demo.DemoCache;
import com.netease.nim.demo.config.preference.Preferences;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ybc on 2018/7/6 0006.
 * 登录
 */
public class LoginActivity extends BaseLoginActivity {
    @BindView(R.id.video_view)
    VideoView videoView;

    protected String longitude = "0"; //经度
    protected String latitude = "0"; // 纬度
    private AbortableFuture<LoginInfo> loginRequestNim;

    @Override
    protected int getLayoutResID() {
        //去除title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_login;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setNeedOnBus(true);
        setupVideo();
        CommonUtils.fuck();
    }

    /**
     * 初始化视频播放
     */
    private void setupVideo() {
        videoView.setOnPreparedListener(mp -> videoView.start());
        videoView.setOnCompletionListener(mp -> videoView.start());
        videoView.setOnErrorListener((mp, what, extra) -> {
            stopPlaybackVideo();
            return true;
        });
        try {
            Uri uri = Uri.parse("android.resource://" + getPackageName() + "/raw/" + R.raw.login);
            videoView.setVideoURI(uri);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!videoView.isPlaying()) {
            videoView.resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (videoView.canPause()) {
            videoView.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlaybackVideo();
    }

    @Override
    public void doOauthVerifySuc(String openid) {
        showRunningDialog();
        ThreeLoginReq threeLoginReq = new ThreeLoginReq();
        threeLoginReq.setOpenid(openid);
        threeLoginReq.setJpush_id(CommonUtils.getRegistrationID(this));
        threeLoginReq.setLatitude(latitude);
        threeLoginReq.setLongitude(longitude);
        startTask(CommonBiz.getInstance().threeLogin(threeLoginReq), userBaseResponse -> {
            Log.e("yubch", "openid:" + openid);
            if (1 != userBaseResponse.code) {
                startActivity(BindActivity.newIntent(this, openid));
                finish();
                return;
            }
            // 云信登录
            final String account = userBaseResponse.data.getWuserTel();
            final String token = userBaseResponse.data.getYunToken();
            loginRequestNim = NimUIKit.login(new LoginInfo(account, token), new RequestCallback<LoginInfo>() {
                @Override
                public void onSuccess(LoginInfo param) {
                    onLoginDone();

                    DemoCache.setAccount(account);
                    saveLoginInfo(account, token);

                    // 初始化消息提醒配置
                    //initNotificationConfig();

                    ToastHelper.show(LoginActivity.this, "登录成功");
                    User user = userBaseResponse.data;
                    CommonUtils.saveUser(LoginActivity.this, user);
                    EventBus.getDefault().post(new LoginEvent());
                    finish();
                }

                @Override
                public void onFailed(int code) {
                    onLoginDone();
                    if (code == 302 || code == 404) {
                        ToastHelper.show(LoginActivity.this, com.netease.nim.demo.R.string.login_failed);
                    } else {
                        ToastHelper.show(LoginActivity.this, "登录失败: " + code);
                    }
                }

                @Override
                public void onException(Throwable exception) {
                    ToastHelper.show(LoginActivity.this, com.netease.nim.demo.R.string.login_exception);
                    onLoginDone();
                }
            });
        });
    }

    private void stopPlaybackVideo() {
        try {
            videoView.stopPlayback();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.layout_wx)
    public void wx() {
        doOauthVerify(SHARE_MEDIA.WEIXIN);
    }

    private void onLoginDone() {
        loginRequestNim = null;
    }

    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }

    @OnClick(R.id.layout_phone)
    public void phone() {
        startActivity(new Intent(this, PhoneLoginActivity.class));
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLocationEvent(LocationEvent locationEvent) {
        longitude = String.valueOf(locationEvent.longitude);
        latitude = String.valueOf(locationEvent.latitude);
    }

    @OnClick(R.id.tv_protocol)
    public void protococol() {
        startActivity(WebActivity.newIntent(this, "用户协议", Constant.ANCHOR_AGREEMENT_URL));
    }
}
